import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:atten_sys/entity/Entity.dart';
import 'package:atten_sys/utils/utils.dart';
import 'package:atten_sys/utils/http.dart';

class DayOff extends StatefulWidget {
  DayOff({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _DayOffState();
  }
}

class _DayOffState extends State<DayOff> {
  DateTime _fromTime;

  DateTime _toTime;

  Excuse _excuse = new Excuse();

  int aid;

  List<Attendance> _aList;

  List<DropdownMenuItem<int>> _items;

  HttpUtil _http = HttpUtil.getInstance();

  TextField buildRichText() {
    return TextField(
      decoration: InputDecoration(
          prefixIcon: Icon(Icons.av_timer),
          labelText: '请假原因',
          hintText: '请写明请假理由',
          border: OutlineInputBorder()),
      maxLength: 150,
      maxLines: 6,
      onChanged: (String value) => _excuse.reason = value,
    );
  }

  bool excuseValidator(Excuse a) {
    if (a.startTime == null || a.endTime == null || a.reason == null) {
      print(a.startTime);
      print(a.endTime);
      print(a.reason);
      print(a.aid);
      return false;
    } else
      return true;
  }

  Align buildSubmitButton() {
    return Align(
      child: SizedBox(
        child: RaisedButton(
          color: Colors.blue,
          colorBrightness: Brightness.dark,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(14))),
          onPressed: () {
            //在提交之前还需要进行数据的检验
            //1.请假日期不能为空
            //2.请假理由不能为空
            //3.请假事件不能为空
            _excuse.startTime = _fromTime;
            _excuse.endTime = _toTime;
            _excuse.aid = aid;

            bool a = excuseValidator(_excuse);
            if (!a) {
              DialogUtil.createDialog(context, '错误', '请将信息填写完整');
              return;
            }
            submitExcuseInfo(_excuse);
          },
          child: Text('提交'),
        ),
      ),
    );
  }

  //获取当前用户的所有attendance
  Future<void> getAllAtten() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    AttendanceList lists = new AttendanceList(attendances: new List());
    Options options = Options(
        headers: {'Authorization': preferences.getString('Authorization')},
        responseType: ResponseType.json);
    dynamic data = await _http.get(
      '/attendance/app/myAttendance',
      options: options
    );
    if (data['success'] == true) {
      print(data['payload']);
      lists = AttendanceList.fromJson(data['payload']);
      _aList = lists.attendances;
      getMenuItem();
    }
  }

  submitExcuseInfo(Excuse excuse) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    dynamic data = await _http.post('/excuse/app/apply',
        data: {
          'reason': excuse.reason,
          'startTime':
              DateUtil.date2FmtStr(excuse.startTime, 'yyyy-MM-dd 00:00:00'),
          'endTime':
              DateUtil.date2FmtStr(excuse.endTime, 'yyyy-MM-dd 00:00:00'),
          'aid': excuse.aid
        },
        options: new Options(headers: {
          'Authorization': preferences.getString('Authorization')
        }));
    if (data['success'] == true) {
      DialogUtil.createDialog(context, '提示', '${data['payload']}');
    }
  }

  getMenuItem() {
    List<DropdownMenuItem<int>> items = new List();
    if (_aList != null && _aList.isNotEmpty) {
      items.clear();
      for (int i = 0; i < _aList.length; i++) {
        DropdownMenuItem<int> item = new DropdownMenuItem(
          child: Text(_aList[i].name),
          value: _aList[i].id,
        );
        items.add(item);
        print('i have added a new item');
      }
    } else {
      items.add(DropdownMenuItem(child: Text('暂无数据')));
    }
    setState(() {
      this._items = items;
      print('items = ${items.length}');
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    print('heioijafwekma');
    super.initState();
    _fromTime = DateTime.now();
    _toTime = DateTime.now();
    aid = null;
    //首先获取attendance的列表
    getAllAtten();
    //然后进行下拉菜单的创建
    print('Enter the init');
  }

  @override
  Widget build(BuildContext context) {
    print('Enter the build');
    // TODO: implement build
    return ListView(
      padding: EdgeInsets.symmetric(horizontal: 40),
      children: <Widget>[
        SizedBox(
          height: 20,
        ),
        _DateTimePicker(
          labelText: '开始日期',
          selectedDate: _fromTime,
          selectDate: (DateTime date) {
            setState(() {
              _fromTime = date;
            });
          },
        ),
        SizedBox(
          height: 25,
        ),
        _DateTimePicker(
          labelText: '结束日期',
          selectedDate: _toTime,
          selectDate: (DateTime d) {
            setState(() {
              _toTime = d;
            });
          },
        ),
        SizedBox(
          height: 25,
        ),
        InputDecorator(
          decoration: const InputDecoration(
              labelText: '考勤事件', contentPadding: EdgeInsets.zero),
          child: DropdownButton<int>(
            value: aid,
            hint: Text('请选择'),
            onChanged: (int newValue) {
              setState(() {
                aid = newValue;
              });
            },
            items: _items,
          ),
        ),
        SizedBox(
          height: 50,
        ),
        buildRichText(),
        buildSubmitButton()
      ],
    );
  }
}

class _InputDropdown extends StatelessWidget {
  const _InputDropdown(
      {Key key,
      this.child,
      this.labelText,
      this.valueText,
      this.valueStyle,
      this.onPressed})
      : super(key: key);

  final String labelText;
  final String valueText;
  final TextStyle valueStyle;
  final VoidCallback onPressed;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onPressed,
      child: InputDecorator(
        decoration: InputDecoration(
          labelText: labelText,
        ),
        baseStyle: valueStyle,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text(valueText, style: valueStyle),
            Icon(Icons.arrow_drop_down,
                color: Theme.of(context).brightness == Brightness.light
                    ? Colors.grey.shade700
                    : Colors.white70),
          ],
        ),
      ),
    );
  }
}

class _DateTimePicker extends StatelessWidget {
  const _DateTimePicker({
    Key key,
    this.labelText,
    this.selectedDate,
    this.selectDate,
  }) : super(key: key);

  final String labelText;
  final DateTime selectedDate;
  final ValueChanged<DateTime> selectDate;

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime.now().add(new Duration(days: -1)),
        lastDate: DateTime.now().add(new Duration(days: 14)),
        locale: Locale('zh'));
    if (picked != null && picked != selectedDate) selectDate(picked);
  }

  @override
  Widget build(BuildContext context) {
    final TextStyle valueStyle = Theme.of(context).textTheme.title;
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        Expanded(
          flex: 4,
          child: _InputDropdown(
            labelText: labelText,
            valueText: DateUtil.date2FmtStr(selectedDate, 'yyyy年 MM月 dd日'),
            valueStyle: valueStyle,
            onPressed: () {
              _selectDate(context);
            },
          ),
        ),
      ],
    );
  }
}
